import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:ichinesereader/constants.dart';
import 'package:ichinesereader/controller/reports.dart';
import 'package:ichinesereader/models/student/assignmentSearchDto.dart';
import 'package:ichinesereader/utils/log.dart';
import 'package:ichinesereader/widgets/grids/currentHomeworkDataGrid.dart';
import 'package:reactive_forms/reactive_forms.dart';
import 'reportsStudentPersonalContent.dart';

class ReportStudentPersonalHomework extends StatefulWidget {
  ReportStudentPersonalHomework({
    Key? key,
    required this.classId,
    required this.userName,
  }) : super(key: key);
  final String classId;
  final String userName;

  @override
  ReportStudentPersonalAssignmentState createState() =>
      ReportStudentPersonalAssignmentState();
}

ValidatorFunction _compareDate(String controlName, String matchingControlName) {
  return (AbstractControl<dynamic> control) {
    final form = control as FormGroup;

    final formControl = form.control(controlName);
    final matchingFormControl = form.control(matchingControlName);

    if (formControl.isNotNull &&
        formControl.value is DateTime &&
        matchingFormControl.isNotNull &&
        matchingFormControl.value is DateTime &&
        formControl.value!.isAfter(matchingFormControl.value!)) {
      matchingFormControl.setErrors({'compareDate': true});
      matchingFormControl.markAsTouched();
    } else {
      matchingFormControl.removeError('compareDate');
    }
    return null;
  };
}

ValidatorFunction _requiredFilter(
    String controlName1, String controlName2, String matchingControlName) {
  return (AbstractControl<dynamic> control) {
    final form = control as FormGroup;

    final formControl1 = form.control(controlName1);
    final formControl2 = form.control(controlName2);
    final matchingFormControl = form.control(matchingControlName);

    if ((formControl1.isNotNull && formControl1.value is DateTime ||
            formControl2.isNotNull && formControl2.value is DateTime) &&
        !matchingFormControl.isNotNull) {
      matchingFormControl.setErrors({'required': true});
      matchingFormControl.markAsTouched();
    } else {
      matchingFormControl.removeError('required');
    }
    return null;
  };
}

class ReportStudentPersonalAssignmentState
    extends State<ReportStudentPersonalHomework> {
  final ReportsController _reportsController = Get.find();
  var box = Hive.box('appconfig');

  final form = FormGroup({
    'from': FormControl<DateTime>(),
    'to': FormControl<DateTime>(),
    'filteredBy': FormControl<String>(),
    'open': FormControl<bool>(),
    'close': FormControl<bool>(),
  }, validators: [
    _compareDate('from', 'to'),
    _requiredFilter('from', 'to', 'filteredBy')
  ]);

  // StudentActivityDto dto = new StudentActivityDto(
  //     from: DateTime.now()
  //         .add(Duration(days: -1 * Constants.InitDay))
  //         .microsecondsSinceEpoch,
  //     to: DateTime.now().millisecondsSinceEpoch);

  @override
  void initState() {
    studentPersonalReportTab = Constants.studentPersonalReportTabs[4];
    if (_reportsController.classstudentreport.value.response != null) {
      _reportsController.classstudentreport.value.response!.list!.clear();
    }
    form.control('from').value = null;
    form.control('to').value = null;
    form.control('filteredBy').value = null;
    form.control('open').value = true;
    form.control('close').value = true;

    fetchOverallData(
        widget.classId,
        widget.userName,
        form.control('from').value,
        form.control('to').value,
        form.control('filteredBy').value,
        form.control('open').value,
        form.control('close').value);
    super.initState();
  }

  void _onCustomTimeUpdate() {
    if (!form.valid) {
      form.markAllAsTouched();
      return;
    } else {
      fetchOverallData(
          widget.classId,
          widget.userName,
          form.control('from').value,
          form.control('to').value,
          form.control('filteredBy').value,
          form.control('open').value,
          form.control('close').value);
    }
  }

  void fetchOverallData(String classId, String userName, DateTime? from,
      DateTime? to, String? filteredBy, bool open, bool close) {
    int? newfrom = from != null ? from.millisecondsSinceEpoch : null;
    int? newto = to != null ? to.millisecondsSinceEpoch : null;
    AssignmentSearchDto dto = new AssignmentSearchDto(
        assignmentType: "ASSIGNMENT",
        live: open,
        past: close,
        sortField: "-created",
        from: newfrom,
        to: newto,
        filteredBy: filteredBy);
    Future.delayed(Duration(milliseconds: 100), () {
      _reportsController.fetchClassStudentReportByClass(classId, userName, dto);
    });
  }

  void _onCustomTimeClear() {
    form.control('from').value = null;
    form.control('to').value = null;
    form.control('filteredBy').value = null;
    fetchOverallData(
        widget.classId,
        widget.userName,
        form.control('from').value,
        form.control('to').value,
        form.control('filteredBy').value,
        form.control('open').value,
        form.control('close').value);
  }

  void resetForm() {
    form.control('from').value = null;
    form.control('to').value = null;
    form.control('filteredBy').value = null;
    form.control('open').value = true;
    form.control('close').value = true;
  }

  @override
  Widget build(BuildContext context) {
    Log.debug('build SchoolAdmin reportsStudentPersonal homework');
    return Center(
        child: Padding(
      padding: const EdgeInsets.all(10),
      child: Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [
        Row(
          children: [
            Expanded(
                child: ReactiveForm(
              formGroup: form,
              child: Column(
                children: [
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceAround,
                    children: <Widget>[
                      Flexible(
                        child: ReactiveTextField<DateTime>(
                          formControlName: 'from',
                          //readOnly: true,
                          decoration: InputDecoration(
                            labelText: 'From'.tr,
                            labelStyle: Theme.of(context).textTheme.titleSmall,
                            suffixIcon: ReactiveDatePicker<DateTime>(
                              formControlName: 'from',
                              firstDate: DateTime(1990),
                              lastDate: DateTime.now(),
                              builder: (context, picker, child) {
                                return IconButton(
                                  onPressed: picker.showPicker,
                                  icon: const Icon(Icons.date_range),
                                );
                              },
                            ),
                          ),
                        ),
                      ),
                      Flexible(
                        child: Padding(
                          padding: const EdgeInsets.symmetric(horizontal: 21.0),
                          child: ReactiveTextField<DateTime>(
                            formControlName: 'to',
                            //readOnly: true,
                            decoration: InputDecoration(
                              labelText: 'To'.tr,
                              labelStyle:
                                  Theme.of(context).textTheme.titleSmall,
                              suffixIcon: ReactiveDatePicker<DateTime>(
                                formControlName: 'to',
                                firstDate: DateTime(1990),
                                lastDate: DateTime.now(),
                                builder: (context, picker, child) {
                                  return IconButton(
                                    onPressed: picker.showPicker,
                                    icon: const Icon(Icons.date_range),
                                  );
                                },
                              ),
                            ),
                            validationMessages: {
                              'compareDate': (error) =>
                                  'Start date must before than end date',
                            },
                          ),
                        ),
                      ),
                      Flexible(
                        child: ReactiveDropdownField<dynamic>(
                          formControlName: 'filteredBy',
                          decoration: InputDecoration(
                              labelText: 'Date Type'.tr,
                              labelStyle:
                                  Theme.of(context).textTheme.titleSmall),
                          onChanged: (value) =>
                              form.control('filteredBy').value = value.value,
                          items: Constants.dateFilters.map((value) {
                            return DropdownMenuItem(
                              value: value.value,
                              child: Text(
                                value.label.toString(),
                                style: Theme.of(context).textTheme.titleSmall,
                                overflow: TextOverflow.ellipsis,
                              ),
                            );
                          }).toList(),
                          validationMessages: {
                            'required': (error) => 'Required',
                          },
                        ),
                      ),
                    ],
                  ),
                  Padding(
                    padding: const EdgeInsets.only(top: 12.0),
                    child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        crossAxisAlignment: CrossAxisAlignment.end,
                        children: [
                          Spacer(),
                          Row(
                            children: [
                              Row(children: [
                                ReactiveCheckbox(formControlName: 'open'),
                                Text("Open".tr)
                              ]),
                              Padding(
                                padding: const EdgeInsets.symmetric(
                                    horizontal: 12.0),
                                child: Row(children: [
                                  ReactiveCheckbox(formControlName: 'close'),
                                  Text("Close".tr)
                                ]),
                              ),
                            ],
                          ),
                          Row(
                            children: [
                              Padding(
                                padding: const EdgeInsets.only(right: 12.0),
                                child: ReactiveFormConsumer(
                                  builder: (context, form, child) {
                                    return ElevatedButton(
                                        child: Text('Go'.tr),
                                        onPressed: _onCustomTimeUpdate);
                                  },
                                ),
                              ),
                              ReactiveFormConsumer(
                                builder: (context, form, child) {
                                  return ElevatedButton(
                                      child: Text('Clear'.tr),
                                      onPressed: _onCustomTimeClear);
                                },
                              ),
                            ],
                          ),
                        ]),
                  ),
                ],
              ),
            )),
          ],
        ),
        Expanded(
          child: _reportsController.obx((data) {
            if (_reportsController.classstudentreport.value.response != null) {
              return Container(
                  margin: EdgeInsets.only(top: 9.0),
                  height: 300,
                  child: CurrentHomeworkDataGrid(_reportsController
                      .classstudentreport.value.response!.list!));
            } else {
              return Text("Data loading");
            }
          }),
        ),
      ]),
    ));
  }
}
